package net.borderwars.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import java.sql.SQLException;

/**
 * @author ehubbard
 *         Date: Apr 21, 2006
 *         Time: 10:02:51 AM
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory;

    static public void init () {
        try {

            AnnotationConfiguration ac = new AnnotationConfiguration ();
            ac.setProperty ("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
            ac.setProperty ("hibernate.show_sql", "true");
            ac.setProperty ("hibernate.hbm2ddl.auto", "update");
            ac.setProperty ("hibernate.connection.username", "sa");
            ac.setProperty ("hibernate.connection.password", "");
            ac.setProperty ("hibernate.connection.url", "jdbc:hsqldb:file:../../db/test");
            ac.setProperty ("hibernate.connection.pool_size", "5");

         //   ac.addAnnotatedClass (net.borderwars.beans.Player.class);
         //   ac.addAnnotatedClass (net.borderwars.beans.Robot.class);

            Class.forName ("org.hsqldb.jdbcDriver");
            sessionFactory = ac.buildSessionFactory ();
        }
        catch (Throwable ex) {
            throw new ExceptionInInitializerError (ex);
        }
    }

    public static void shutdown () throws SQLException {
        DBSession s = getSession ();
        s.connection ().prepareStatement ("SHUTDOWN").execute ();
        s.close ();
        sessionFactory.close ();
    }

    public static void setupDumbDatabase () {
        init ();
//        DBSession s = getSession ();
//        Player p = new Player ("Inconnu");
//        p.setPassword ("unknown");
//
//        Robot r = new Robot ("Sniper");
//        r.setAuthor (p);
//        r.setSource ("public class Sniper extents Robot   {\n} ");
//        s.persist (r);
//
//        r = new Robot ("Target");
//        r.setPublicDomain (true);
//        s.persist (r);
//
//        p.getOwnSource ().add (r);
//
//        s.persist (p);
//
//        s.flush ();
//        s.close ();
    }

    public static DBSession getSession () throws HibernateException {
        Session rtn = sessionFactory.openSession ();
        return (new DBSession (rtn));
    }

    public static void main (String[] args) {
        try {
            setupDumbDatabase ();
        }
        catch (ExceptionInInitializerError e) {
            System.exit (1);
        }
    }
}